package com.myreminder.server;

import java.util.Date;

import com.myreminder.data.Reminder;
import com.myreminder.data.User;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.myreminder.server.DAO;
import com.myreminder.service.FacebookUserService;

/**
 * The server side implementation of the RPC service.
 */
public class userServlet extends RemoteServiceServlet implements FacebookUserService {
	
	@Override
	public User loginOrRegister(String facebookID, String name, String email) {
		new DAO();
		Objectify db = ObjectifyService.begin();
		
		User u = db.find(User.class,facebookID);
		if(u == null){
			u = new User(name,email,facebookID);
			db.put(u);
		} else {
			Iterable<Reminder> reminder = db.query(Reminder.class).filter("user", u);
			for(Reminder r : reminder){
				u.addReminder(r);
			}
		}
		return u;
	}

	@Override
	public void removeReminder(Reminder r) {
		new DAO();
		Objectify db = ObjectifyService.begin();
		db.delete(r);
	}

	@Override
	public Reminder createReminder(User u, String title, Date date,	String description) {
		new DAO();
		Reminder r = new Reminder(new Key<User>(User.class,u.facebookID), date, title, description);
		Objectify db = ObjectifyService.begin();
		db.put(r);
		return r;
	}

}
